package com.prizedraw.prize_draw.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.prizedraw.prize_draw.common.exception.CaptchaException;
import com.prizedraw.prize_draw.common.lang.Const;
import com.prizedraw.prize_draw.util.RedisUtil;
import freemarker.template.utility.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    LoginFailureHandler loginFailureHandler;

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = httpServletRequest.getRequestURI();
        if ("/login".equals(requestURI) && httpServletRequest.getMethod().equals("POST")){
            try {
                validate(httpServletRequest);
                log.info("验证码校验成功！");
            }catch (CaptchaException e){
                loginFailureHandler.onAuthenticationFailure(httpServletRequest,httpServletResponse,e);
            }

        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }

    /**
     * 校验验证码逻辑
     * @param httpServletRequest
     */
    private void validate(HttpServletRequest httpServletRequest) {
        String code = httpServletRequest.getParameter("code");
        String codeKey = httpServletRequest.getParameter("codeKey");

        if (StringUtils.isBlank(code) || StringUtils.isBlank(codeKey)){
            throw new CaptchaException("验证码错误");
        }
        if(!code.equalsIgnoreCase(redisUtil.hget(Const.CAPTCHA_KEY,codeKey).toString())){
            throw new CaptchaException("验证码错误");
        }
        // 一次性使用
        redisUtil.hdel(Const.CAPTCHA_KEY, codeKey);

    }
}
